package com.xiaoKe.zhonghzu.global.base;

/**
 * @ProjectName : xiaoke-pad-zhongzhu
 * @Author : Shijingna
 * @Time : 2024/8/1 14:24
 * @Description : 文件描述
 */
import android.content.Context;
import android.util.DisplayMetrics;
import android.view.View;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

public class AdaptiveGridLayoutManager extends GridLayoutManager {

    private static final int MIN_ITEM_WIDTH_DP = 100; // 设置最小 item 宽度（dp）
    private int minItemWidthPx;
    private int screenWidth;
    private boolean isScrolling;

    public AdaptiveGridLayoutManager(Context context, int spanCount) {
        super(context, spanCount);
        this.minItemWidthPx = dpToPx(context, MIN_ITEM_WIDTH_DP);
        this.screenWidth = getScreenWidth(context);
    }

    @Override
    public void onLayoutChildren(RecyclerView.Recycler recycler, RecyclerView.State state) {
        super.onLayoutChildren(recycler, state);
        if (!isScrolling) {
            adjustSpanCount();
        }
    }

    @Override
    public void onScrollStateChanged(int state) {
        super.onScrollStateChanged(state);
        if (state == RecyclerView.SCROLL_STATE_DRAGGING || state == RecyclerView.SCROLL_STATE_SETTLING) {
            isScrolling = true;
        } else if (state == RecyclerView.SCROLL_STATE_IDLE) {
            isScrolling = false;
            adjustSpanCount();
        }
    }

    private void adjustSpanCount() {
        int itemWidth = getItemWidth();
        int spanCount = determineSpanCount(itemWidth);
        setSpanCount(spanCount);
    }

    private int determineSpanCount(int itemWidth) {
        if (itemWidth < minItemWidthPx) {
            return 1;
        }
        return Math.max(1, screenWidth / itemWidth);
    }

    private int getItemWidth() {
        int visibleItemCount = getChildCount();
        if (visibleItemCount == 0) return minItemWidthPx;

        int totalWidth = 0;
        for (int i = 0; i < visibleItemCount; i++) {
            View child = getChildAt(i);
            if (child != null) {
                totalWidth += child.getWidth();
            }
        }
        return Math.max(totalWidth / visibleItemCount, minItemWidthPx);
    }

    private int getScreenWidth(Context context) {
        DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();
        return displayMetrics.widthPixels;
    }

    private int dpToPx(Context context, int dp) {
        float density = context.getResources().getDisplayMetrics().density;
        return Math.round(dp * density);
    }
}